package logger

import (
	"gitee.com/filters/reader/wviper"
	"gitee.com/filters/utils/character"
	"gitee.com/filters/utils/errv"
	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
	"gopkg.in/natefinch/lumberjack.v2"
	"os"
	"time"
)

const (
	RequestId = "RequestId"
	Logger    = "Logger"
	LogPathName = "log_file_path"
	LogExtName = "log_file_ext"
)

type SeverityHook struct {
	zerolog.Logger
	Hooks []zerolog.Hook
	writePath string `json:"write_path"`
	logExt    string `json:"log_ext"`
	error
}

func WithLogExt(ext string) HookOption {
	return func(opt *SeverityHook) {
		opt.logExt = ext
	}
}

func WithWritePath(path string) HookOption {
	return func(opt *SeverityHook) {
		opt.writePath = path
	}
}

type HookOption func(s *SeverityHook)

func NewLog(options ...HookOption) *SeverityHook {
	hook := &SeverityHook{
		logExt: "log",
	}
	for _, opt := range options {
		opt(hook)
	}
	return hook
}

func (h *SeverityHook) WrapFormat() error {
	name := time.Now().Format(time.DateOnly)
	logRotate := &lumberjack.Logger{
		Filename:   h.writePath + "/" + name + "." + h.logExt, // 文件位置
		MaxSize:    10,                                        // megabytes，M 为单位，达到这个设置数后就进行日志切割
		MaxBackups: 3,                                         // 保留旧文件最大份数
		MaxAge:     30,                                        //days ， 旧文件最大保存天数
		Compress:   true,                                      // disabled by default，是否压缩日志归档，默认不压缩
	}
	zerolog.TimeFieldFormat = time.DateTime
	consoleWriter := zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.DateTime}
	multi := zerolog.MultiLevelWriter(consoleWriter, logRotate)
	loger := log.Output(multi).With().Logger().Hook(h.Hooks...)
	loger.UpdateContext(func(c zerolog.Context) zerolog.Context {
		return c.Str(RequestId, character.GetUid())
	})
	log.Logger = loger
	h.Logger = log.Logger
	return h.error
}

// HandleFunc 钩子使用
func (h *SeverityHook) HandleFunc(hooks ...zerolog.Hook) *SeverityHook {
	h.Hooks = hooks
	return h
}

func (h *SeverityHook) CurLog(str ...string) *SeverityHook {
	var infoString = wviper.NewReader().Get(Logger)
	if len(str) > 0 {
		infoString = wviper.NewReader().Get(str[0])
	}
	if infoString == nil {
		h.error = errv.New(-20008,"未找到配置文件")
		return h
	}
	h.logExt = infoString.(map[string]interface{})[LogExtName].(string)
	h.writePath = infoString.(map[string]interface{})[LogPathName].(string)
	return h
}
